// 断开重连 不好用
class Socket{
  wsUrl;
  constructor(wsUrl){
    this.wsUrl = wsUrl
  }
  ModeCode = {
    MSG:'message',//普通消息
    HEART_BEAT:'heart_beat' //心跳检测消息
  }
  ws = null
  webSocketState = false;//WebSocket连接状态
  heartBeat = {
    time: 10*1000, //心跳检测间隔时间
    timeout:10*1000, //心跳超时间隔
    reconnect: 10 * 1000  //断线重连时间
  }
  reconnectTimer = null // 断线重连时间器
  connectWebSocket(){
    this.ws = new WebSocket(this.wsUrl)
    this.init()
  }
  //初始化函数
  init(){
    this.ws.addEventListener('open', ()=>{
      // ws状态 设置为连接: true
      this.webSocketState = true
      //是否启动心跳检测
      this.heartBeat && this.heartBeat.time ? this.startHeartBeat(this.heartBeat.time) : ''
    }, false); // 成功回调
    
    this.ws.addEventListener('message', (e) => {
      console.log('e',e.data)
      let result = e.data != '连接成功' && JSON.parse(e.data)
      console.log('result', result)
      // const data = JSON.parse(e.data)
      // switch (data.ModeCode) {
      //   case this.ModeCode.MSG:
      //     console.log('普通消息')
      //     break;
      
      //   case this.ModeCode.HEART_BEAT:
      //     this.webSocketState = true
      //     console.log('心跳消息', data.msg)
      //     break;
      // }
    })
    this.ws.addEventListener('close',(e)=>{
      this.webSocketState = false
      console.log('关闭了连接',e)
      // this.startHeartBeat(this.heartBeat.time);
      this.reconnectWebSocket()
    })
    this.ws.addEventListener('error',(e)=>{
      this.webSocketState = false;
      this.reconnectWebSocket() // 重新连接
      console.log('连接发生了错误', e)
    })
  }
  //心跳检测初始化函数
  startHeartBeat(time){
    setTimeout(() => {
      // this.ws.send("HeartBeat");
      // this.ws.send(
      //   JSON.stringify({
      //     // ModeCode:this.ModeCode.HEART_BEAT,
      //     // msg:new Date()
      //   })
      // )
      this.waitingServer();
    }, time);
  }
  //延时等待服务端响应，通过webSocketState判断是否连线成功
  waitingServer(){
    this.webSocketState = false
    setTimeout(() => {
      if(this.webSocketState){
        this.startHeartBeat(this.heartBeat.time);
        return
      } 
      console.log('心跳无响应,已经断线了')
      try{
        this.ws.close()
      }catch(e){
        console.log('连接已关闭')
      }
      this.reconnectWebSocket()
    }, this.heartBeat.timeout);
  }
  //重新连接
  reconnectWebSocket(){
    this.reconnectTimer = setTimeout(() => {
      this.reconnectWs();
    }, this.heartBeat.reconnect);
  }
  //控制执行
  reconnectWs(){
    if(!this.ws){
      // 第一次执行，初始化
      this.connectWebSocket()
    }
    if(this.ws && this.reconnectTimer){
      // 防止多个WebSocket同时执行
      clearInterval(this.reconnectTimer);
      this.ws.reconnectTimer = null
      this.reconnectWebSocket()
    }
  }
}

export default Socket